<template>
  <div class="app_content">
      <el-form :inline="true" ref="queryForm" :model="queryParams" class="demo-form-inline" :size="size" v-if="showSearch">
      <el-form-item label="角色名称" prop="roleName">
      <el-input v-model="queryParams.roleName" clearable placeholder="角色名称" style="width: 240px"/>
      </el-form-item>
      <el-form-item label="权限字符" prop="roleKey">
      <el-input v-model="queryParams.roleKey" clearable placeholder="权限字符" style="width: 240px"/>
      </el-form-item>
      <el-form-item label="创建时间" >
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="querySubmit">
          <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-search'"/>
          搜索</el-button>
        <el-button   @click="resetSubmit">
          <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-redo'"/>
          重置</el-button>
      </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            :size="size"
            @click="handleAdd"
            v-hasRole="['system:role:add']">
          <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-add-one'"/>
          新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            :size="size"
            :disabled="single"
            @click="handleEdit"
            v-hasRole="['system:role:edit']"
          >
          <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-edit-one'"/>
          修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            :size="size"
            :disabled="multiple"
            @click="handleDelete"
            v-hasRole="['system:role:remove']"
          >
          <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-delete-five'"/>
          删除</el-button>
        </el-col>
        <!-- <el-col :span="1.5">
          <Export  :dc="true"  :dr="true" :exlData="tableData" :tHead="staticData.ExportHead" :tName="'导出的标题'" ></Export>
        </el-col>
  -->
        <!-- <RightToolbar :showSearch="showSearch" @queryTable="getList" :columns="columns"/> -->
        <RightToolbar :showSearch="showSearch" @queryTable='getList' @showSearchClick='showSearchClick' :columns="columns"/>
      </el-row>
      <el-table :border="$border" v-loading="loading" :data="tableData" :height="maxHeight"  style="width: 100%" @selection-change="handleSelectionChange"  :size="size"
      >
      <el-table-column type="selection" width="55" />
      <el-table-column label="编号" prop="id" show-overflow-tooltip key="id" v-if="columns[0].visible">
        <template #default="scope">{{scope.$index+1}}</template>
        </el-table-column>
      <el-table-column label="角色名称" prop="roleName" show-overflow-tooltip key="roleName"  v-if="columns[1].visible"/>
      <el-table-column label="权限字符" prop="roleKey" show-overflow-tooltip key="roleKey"  v-if="columns[2].visible"/>
      <el-table-column label="显示顺序" prop="roleSort" show-overflow-tooltip key="roleSort"  v-if="columns[3].visible"/>
      <el-table-column label="状态" prop="status" show-overflow-tooltip key="status"  v-if="columns[4].visible">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
        </el-table-column>
      <el-table-column label="创建时间" prop="createTime" show-overflow-tooltip key="createTime"  v-if="columns[5].visible"/>
      <el-table-column label="操作" fixed="right" align="center"  width="300px">
      <template #default="scope" >
          <el-button :size="size"  v-hasRole="['system:role:edit']" v-if="scope.row.roleId !== 1" type="success"  text @click="handleEdit(scope.row)"
          ><component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-edit-one'"/>修改</el-button>
          <el-button
          v-if="scope.row.roleId !== 1"
          :size="size"
          type="danger"
          text
          v-hasRole="['system:role:remove']"
          @click="handleDelete(scope.row)"
          ><component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-delete-five'"/>删除</el-button>
          <el-dropdown :size="size" v-if="scope.row.roleId !== 1"   @command="(command) => handleCommand(command, scope.row)">
            <el-button class="el-dropdown-link" text :size="size">
              <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-more'"/>更多
              </el-button>
              <template #dropdown>
                <el-dropdown-menu >
                  <div v-hasRole="['system:role:edit']">
                <el-dropdown-item command="handleDataScope"
                  >
                  <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-internal-data'"/>
                  数据权限</el-dropdown-item>
                  </div>
                  <div v-hasRole="['system:role:edit']">
                <el-dropdown-item command="handleAuthUser" 
                  >
                  <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-every-user'"/>
                  分配用户</el-dropdown-item>
                  </div>

              </el-dropdown-menu>
              </template>
            </el-dropdown>
          
      </template>
      </el-table-column>
  </el-table>
  <div style="margin-top:10px;position: absolute;right: 0;margin-right:20px">
      <el-pagination
        v-model:currentPage="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 30, 40]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
  </div>
  <!-- <el-dialog  v-model="open"  :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false" width="600px" append-to-body draggable :fullscreen="fullscreen">
      <template #header="{close,titleId, titleClass }">
      <div class="my-header">
        <span :id="titleId" :class="titleClass">{{title}}</span>
        <div>
          <component
        style="cursor:pointer;line-height: 24px;margin-right:10px;"
        v-if="fullscreen==false"
              @click="fullscreen=true"
              class="menu-icon"
              theme="outline"
              size="14"
              strokeWidth="3"
              :is="'icon-full-screen-one'"
            />
            <component
            v-else
        style="cursor:pointer;line-height: 24px;margin-right:10px;"
              @click="fullscreen=false"
              class="menu-icon"
              theme="outline"
              size="14"
              strokeWidth="3"
              :is="'icon-off-screen-one'"
            />
        <component
        style="cursor:pointer;line-height: 24px;"
              @click="close"
              class="menu-icon"
              theme="outline"
              size="14"
              strokeWidth="3"
              :is="'icon-close'"
            />
        </div>
        
      </div>
    </template>
    <el-form ref="formDataRef" :model="formData" :rules="rules" :size="size"  label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="formData.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item prop="roleKey">
          <template #label>
            <el-tooltip content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasRole('admin')`)" placement="top">
              <div style=" margin-top: 1px;"><icon-info theme="outline" size="16" fill="#999" /></div>
            </el-tooltip>
            权限字符
          </template>
          <el-input v-model="formData.roleKey" placeholder="请输入权限字符" />
        </el-form-item>
        <el-form-item label="角色顺序" prop="roleSort">
          <el-input-number v-model="formData.roleSort" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="formData.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
              >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>
          <el-checkbox v-model="formData.menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')">父子联动</el-checkbox>
          <el-tree 
            class="tree-border"
            show-checkbox
            ref="menuRef"  
            node-key="id" 
            :data="menuOptions" 
            :props="defaultProps" 
            :check-strictly="!formData.menuCheckStrictly"
            empty-text="加载中，请稍候"
             />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="formData.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div  class="dialog-footer">
        <el-button type="primary" @click="submitForm" :size="size">确 定</el-button>
        <el-button @click="cancel" :size="size">取 消</el-button>
      </div>
      </template>
    </el-dialog> -->

    <el-drawer
      :title="title"
      v-model="open"
      direction="rtl"
      destroy-on-close
      size="50%"
      :close-on-click-modal="false"
    >
    <el-form ref="formDataRef" :model="formData" :rules="rules" :size="size"  label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="formData.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item prop="roleKey">
          <template #label>
            <el-tooltip content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasRole('admin')`)" placement="top">
              <div style=" margin-top: 1px;"><icon-info theme="outline" size="16" fill="#999" /></div>
            </el-tooltip>
            权限字符
          </template>
          <el-input v-model="formData.roleKey" placeholder="请输入权限字符" />
        </el-form-item>
        <el-form-item label="角色顺序" prop="roleSort">
          <el-input-number v-model="formData.roleSort" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="formData.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
              >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>
          <el-checkbox v-model="formData.menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')">父子联动</el-checkbox>
          <el-tree 
            class="tree-border"
            show-checkbox
            ref="menuRef"  
            node-key="id" 
            :data="menuOptions" 
            :props="defaultProps" 
            :check-strictly="!formData.menuCheckStrictly"
            empty-text="加载中，请稍候"
             />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="formData.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div  class="dialog-footer">
          <el-button type="primary" @click="submitForm" :size="size">
          <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-correct'"/>
          确 定</el-button>
        <el-button @click="cancel" :size="size">
          <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-return'"/>
          取 消</el-button>
      </div>
      </template>
  </el-drawer>

    <!-- <el-dialog  v-model="openDataScope"  :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false" width="600px" append-to-body draggable :fullscreen="fullscreen">
      <template #header="{close,titleId, titleClass }">
      <div class="my-header">
        <span :id="titleId" :class="titleClass">{{title}}</span>
        <div>
          <component
        style="cursor:pointer;line-height: 24px;margin-right:10px;"
        v-if="fullscreen==false"
              @click="fullscreen=true"
              class="menu-icon"
              theme="outline"
              size="14"
              strokeWidth="3"
              :is="'icon-full-screen-one'"
            />
            <component
            v-else
        style="cursor:pointer;line-height: 24px;margin-right:10px;"
              @click="fullscreen=false"
              class="menu-icon"
              theme="outline"
              size="14"
              strokeWidth="3"
              :is="'icon-off-screen-one'"
            />
        <component
        style="cursor:pointer;line-height: 24px;"
              @click="close"
              class="menu-icon"
              theme="outline"
              size="14"
              strokeWidth="3"
              :is="'icon-close'"
            />
        </div>
        
      </div>
    </template>
    <el-form ref="formDataRef" :model="formData"  :size="size"  label-width="100px">
      <el-form-item label="角色名称">
          <el-input v-model="formData.roleName" :disabled="true" />
        </el-form-item>
        <el-form-item label="权限字符">
          <el-input v-model="formData.roleKey" :disabled="true" />
        </el-form-item>
        <el-form-item label="权限范围">
          <el-select v-model="formData.dataScope" @change="dataScopeSelectChange">
            <el-option
              v-for="item in dataScopeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据权限" v-show="formData.dataScope == 2">
          <el-checkbox v-model="deptExpand" @change="handleCheckedTreeExpand($event, 'dept')">展开/折叠</el-checkbox>
          <el-checkbox v-model="deptNodeAll" @change="handleCheckedTreeNodeAll($event, 'dept')">全选/全不选</el-checkbox>
          <el-checkbox v-model="formData.deptCheckStrictly" @change="handleCheckedTreeConnect($event, 'dept')">父子联动</el-checkbox>
          <el-tree
            class="tree-border"
            :data="deptOptions"
            show-checkbox
            default-expand-all
            ref="deptRef"
            node-key="id"
            :check-strictly="!formData.deptCheckStrictly"
            empty-text="加载中，请稍候"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
      </el-form>
      <template #footer>
        <div  class="dialog-footer">
        <el-button type="primary" @click="submitFormDataScope" :size="size">确 定</el-button>
        <el-button @click="cancelDataScope" :size="size">取 消</el-button>
      </div>
      </template>
    </el-dialog> -->
    <el-drawer
      :title="title"
      v-model="openDataScope"
      direction="rtl"
      destroy-on-close
      size="50%"
      :close-on-click-modal="false"
    >
    <el-form ref="formDataRef" :model="formData"  :size="size"  label-width="100px">
      <el-form-item label="角色名称">
          <el-input v-model="formData.roleName" :disabled="true" />
        </el-form-item>
        <el-form-item label="权限字符">
          <el-input v-model="formData.roleKey" :disabled="true" />
        </el-form-item>
        <el-form-item label="权限范围">
          <el-select v-model="formData.dataScope" @change="dataScopeSelectChange">
            <el-option
              v-for="item in dataScopeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据权限" v-show="formData.dataScope == 2">
          <el-checkbox v-model="deptExpand" @change="handleCheckedTreeExpand($event, 'dept')">展开/折叠</el-checkbox>
          <el-checkbox v-model="deptNodeAll" @change="handleCheckedTreeNodeAll($event, 'dept')">全选/全不选</el-checkbox>
          <el-checkbox v-model="formData.deptCheckStrictly" @change="handleCheckedTreeConnect($event, 'dept')">父子联动</el-checkbox>
          <el-tree
            class="tree-border"
            :data="deptOptions"
            show-checkbox
            default-expand-all
            ref="deptRef"
            node-key="id"
            :check-strictly="!formData.deptCheckStrictly"
            empty-text="加载中，请稍候"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
      </el-form>
      <template #footer>
        <div  class="dialog-footer">
          <el-button type="primary" @click="submitFormDataScope" :size="size">
          <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-correct'"/>
          确 定</el-button>
        <el-button @click="cancelDataScope" :size="size">
          <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-return'"/>
          取 消</el-button>
      </div>
      </template>
    </el-drawer>
  </div>
  
</template>

<script  >
import RightToolbar from '@/components/RightToolbar/index.vue';
import { listRole, getRole, delRole, addRole, updateRole, dataScope, changeRoleStatus,deptTreeSelect} from "@/api/system/role";
import { treeselect as menuTreeselect, roleMenuTreeselect } from "@/api/system/menu";
import { computed, ref ,reactive,onMounted,getCurrentInstance,toRefs, nextTick} from 'vue'
import { useStore } from 'vuex';
import { useI18n } from 'vue-i18n';
import {
Delete,
Edit,
Plus,
User,
Histogram,
DArrowRight
} from '@element-plus/icons-vue'

export default defineComponent({
  components:{
    DArrowRight,
    RightToolbar
  },
setup(){
  const { proxy } = getCurrentInstance();//关键代码
  const queryForm=ref(null)
  const formDataRef=ref()
  const { t } = useI18n();
  const menuRef=ref(ElTree)
  const deptRef=ref(ElTree)
  const store = useStore();
  const staticData=reactive({
    formData:{
     
    },
    // 表单校验
    rules: {
        roleName: [
          { required: true, message: "角色名称不能为空", trigger: "blur" }
        ],
        roleKey: [
          { required: true, message: "权限字符不能为空", trigger: "blur" }
        ],
        roleSort: [
          { required: true, message: "角色顺序不能为空", trigger: "blur" }
        ]
    },
    defaultProps: {
        children: "children",
        label: "label"
    },
    menuefaultexpandedkeys:[],
    menuExpand: false,
    menuNodeAll: false,
    deptExpand: true,
    deptNodeAll: false,
    statusOptions:[],
     // 菜单树选项
     menuOptions: [],
     deptOptions:[],
     // 数据范围选项
     dataScopeOptions: [
        {
          value: "1",
          label: "全部数据权限"
        },
        {
          value: "2",
          label: "自定数据权限"
        },
        {
          value: "3",
          label: "本部门数据权限"
        },
        {
          value: "4",
          label: "本部门及以下数据权限"
        },
        {
          value: "5",
          label: "仅本人数据权限"
        }
      ],
    maxHeight:store.getters['setting/mode']=='horizontal'?document.body.clientHeight - 265:store.getters['setting/isFullScreen']!=false ?document.body.clientHeight - 360:document.body.clientHeight - 320 ,
    roleName:[],
    ids:[],
    //是否全屏
    fullscreen:false,
    fullscreen1:false,
    // 弹出层标题
    title: "",
      // 是否显示弹出层
    open: false,
    openDataScope:false,
    single:true,
    multiple:true,
    showSearch:true,
    background:false,
    disabled :false,
    search:'',
    tableData:[],
    // 日期范围
    dateRange: [],
    // 查询参数
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        roleName: undefined,
        roleKey: undefined,
        status: undefined
    },
    total:0,
    loading:true, 
    ExportHead:{
      id: "编号",
      name: "角色名称",
      age: "权限字符",
      xb: "显示顺序",
      des: "状态",
      date: "创建时间",
    },
    // 列信息
    columns: [
      { key: 0, label: `编号`, visible: true },
      { key: 1, label: `角色名称`, visible: true },
      { key: 2, label: `权限字符`, visible: true },
      { key: 3, label: `显示顺序`, visible: true },
      { key: 4, label: `状态`, visible: true },
      { key: 5, label: `创建时间`, visible: true },
      
    ],
  })
  const size = computed(() => {
        return store.getters['setting/size'];
  });
  const small =computed(() => {
    return size.value=='small'?true:false
  });
  const filterTableData = computed(() =>
    staticData.tableData.filter(
      (data) =>
        !staticData.search.value ||
        data.name.toLowerCase().includes(staticData.search.value.toLowerCase())
    )
  )
  onMounted(() => {
    proxy.$getDicts("sys_normal_disable").then(response => {
        staticData.statusOptions = response.data;
      });
      proxy.getList()
    })
  const tableData= [
{
  id:1,
  name: '张三',
  age:18,
  xb:'男',
  des:'用来测试的用户',
  date: '2016-05-03'
 
},
{
  id:2,
  name: '李白',
  age:45,
  xb:'男',
  des:'用来测试的用户',
  date: '2016-05-03'
},
{
  id:3,
  name: '李四',
  age:22,
  xb:'男',
  des:'用来测试的用户',
  date: '2016-05-03'
},
{
  id:4,
  name: '貂蝉',
  age:14,
  xb:'女',
  des:'用来测试的用户',
  date: '2016-05-03'
},
    ]
     /**
   * 重置表单效验方法
   */
  const resetForm = (formEl) => {
    if (!formEl.value) return
    formEl.value.resetFields()
  }
  const methods = {
     getList(){
        staticData.loading = true;
        listRole(proxy.$addDateRange(staticData.queryParams, staticData.dateRange)).then(
          response => {
            staticData.tableData = response.rows;
            staticData.total = response.total;
            staticData.loading = false;
          }
      );
     },
     // 角色状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$confirm('确认要"' + text + '""' + row.roleName + '"角色吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return changeRoleStatus(row.roleId, row.status);
        }).then(() => {
          this.msgSuccess(text + "成功");
        }).catch(function() {
          row.status = row.status === "0" ? "1" : "0";
        });
    },
    cancel(){
      staticData.open=false
    },
    cancelDataScope(){
      staticData.openDataScope=false
    },
    /** 选择角色权限范围触发 */
    dataScopeSelectChange(value) {
      if(value !== '2') {
        deptRef.value.setCheckedKeys([]);
      }
    },
    /** 根据角色ID查询部门树结构 */
    getDeptTree(roleId) {
      return deptTreeSelect(roleId).then(response => {
        staticData.deptOptions = response.depts;
        return response;
      });
    },
    /** 分配数据权限操作 */
    handleDataScope(row) {
      proxy.reset();
      const deptTreeSelect = proxy.getDeptTree(row.roleId);
      getRole(row.roleId).then(response => {
        staticData.formData = response.data;
        staticData.openDataScope = true;
        nextTick(() => {
          deptTreeSelect.then(res => {
            deptRef.value.setCheckedKeys(res.checkedKeys);
          });
        });
        staticData.title = "分配数据权限";
      });
    },
    /** 分配用户操作 */
    handleAuthUser: function(row) {
      const roleId = row.roleId;
      this.$router.push({
        path:'/system/auth-user',
        query:{
          roleId:roleId
        }});
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleDataScope":
          proxy.handleDataScope(row);
          break;
        case "handleAuthUser":
          proxy.handleAuthUser(row);
          break;
        default:
          break;
      }
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type == 'menu') {
        let treeList = staticData.menuOptions;
        nextTick(()=>{
        for (let i = 1; i < treeList.length; i++) {
          menuRef.value.store.nodesMap[treeList[i].id].expanded = value;
        }
        
      })
      } else if (type == 'dept') {
        let treeList = staticData.deptOptions;
        for (let i = 1; i < treeList.length; i++) {
          deptRef.value.store.nodesMap[treeList[i].id].expanded = value;
        }
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type == 'menu') {
        menuRef.value.setCheckedNodes(value ? staticData.menuOptions: []);
      } else if (type == 'dept') {
        deptRef.value.setCheckedNodes(value ? staticData.deptOptions: []);
      }
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (type == 'menu') {
        staticData.formData.menuCheckStrictly = value ? true: false;
      } else if (type == 'dept') {
        staticData.formData.deptCheckStrictly = value ? true: false;
      }
    },
     /**
      * 显示或隐藏搜索条件
      **/
     showSearchClick(data){
       staticData.showSearch=data
     },
     /**表格多选 */
     handleSelectionChange(selection){
      staticData.ids = selection.map(item => item.roleId);
      staticData.roleName = selection.map(item => item.roleName);
      staticData.single = selection.length != 1;
      staticData.multiple = !selection.length;

    },
    /** 查询菜单树结构 */
    getMenuTreeselect() {
      menuTreeselect().then(response => {
        staticData.menuOptions = response.data;
      });
    },
    /** 根据角色ID查询菜单树结构 */
    getRoleMenuTreeselect(roleId) {
      return roleMenuTreeselect(roleId).then(response => {
        staticData.menuOptions = response.menus;
        return response;
      });
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = menuRef.value.getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = menuRef.value.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
     // 所有部门节点数据
     getDeptAllCheckedKeys() {
      // 目前被选中的部门节点
      let checkedKeys = deptRef.value.getCheckedKeys();
      // 半选中的部门节点
      let halfCheckedKeys = deptRef.value.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    // 表单重置
    reset() {
      staticData.menuExpand = false,
      staticData.menuNodeAll = false,
      staticData.deptExpand = true,
      staticData.deptNodeAll = false,
      staticData.formData = {
        roleId: undefined,
        roleName: undefined,
        roleKey: undefined,
        roleSort: 0,
        status: "0",
        menuIds: [],
        deptIds: [],
        menuCheckStrictly: true,
        deptCheckStrictly: true,
        remark: undefined
      };
      resetForm(formDataRef)
    },
     handleAdd(row){
      proxy.reset();
      staticData.fullscreen=false
      staticData.title='添加角色'
      proxy.getMenuTreeselect()
      staticData.open=true
    },
    

    handleEdit(row){
      proxy.reset();
      const roleId = row.roleId || staticData.ids
      const roleMenu = proxy.getRoleMenuTreeselect(roleId);
      staticData.fullscreen=false
      getRole(roleId).then(response => {
        staticData.formData = response.data;
        staticData.formData.roleSort=parseInt(response.data.roleSort)
        staticData.open = true;
        staticData.title = "修改角色";
        nextTick(() => {
          roleMenu.then(res => {
            let checkedKeys = res.checkedKeys
            checkedKeys.forEach((v) => {
                nextTick(()=>{
                    menuRef.value.setChecked(v, true ,false);
                })
            })
          });
        });
        
      });
    },
    handleDelete(row){
      const roleIds = row.roleId || staticData.ids;
      const roleName = row.roleName || staticData.roleName;
      
      ElMessageBox.confirm('是否确认删除角色名称为"' + roleName + '"的数据项？', t('confirm.title'), {
          confirmButtonText: t('btn.confirm'),
          cancelButtonText: t('btn.cancel'),
          type: "warning"
        })
      .then(function() {
        return delRole(roleIds);
      }).then(() => {
        proxy.getList();
        proxy.Success("删除成功");
      }).catch(() => {});
    },
    submitForm(){
      formDataRef.value.validate(valid => {
        if (valid) {
          if (staticData.formData.roleId != undefined) {
            staticData.formData.menuIds = proxy.getMenuAllCheckedKeys();
            updateRole(staticData.formData).then(response => {
              proxy.Success("修改成功");
              staticData.open = false;
              proxy.getList();
            });
          } else {
            staticData.formData.menuIds = proxy.getMenuAllCheckedKeys();
            addRole(staticData.formData).then(response => {
              proxy.Success("新增成功");
              staticData.open = false;
              proxy.getList();
            });
          }
        }
      });
    },
    /** 提交按钮（数据权限） */
    submitFormDataScope() {
      if (staticData.formData.roleId != undefined) {
        staticData.formData.deptIds = proxy.getDeptAllCheckedKeys();
        dataScope(staticData.formData).then(response => {
          proxy.Success("修改成功");
          staticData.openDataScope = false;
          proxy.getList();
        });
      }
    },
    resetSubmit(){
      staticData.dateRange=[]
      queryForm.value.clearValidate()
      queryForm.value.resetFields();
      proxy.getList()
    },
    querySubmit(){
      staticData.queryParams.pageNum = 1;
      proxy.getList()
    },
    handleSizeChange (val) {
      console.log(`${val} items per page`)
      staticData.queryParams.pageSize =val;
      proxy.getList()
    },
    handleCurrentChange(val){
      console.log(`current page: ${val}`)
      staticData.queryParams.pageNum =val;
      proxy.getList()
    }
   }
    return {
      Delete,
      Edit,
      Plus,
      User,
      Histogram,
      size,
      small,
      queryForm,
      menuRef,
      deptRef,
      formDataRef,
      ...methods,
      filterTableData,
      ...toRefs(staticData)
    }
}


})



</script>

<style scoped>
.demo-pagination-block + .demo-pagination-block {
margin-top: 10px;
}
.demo-pagination-block .demonstration {
margin-bottom: 16px;
}
</style>
<style scoped>
.app_content{
  
  margin-top: 30px;
  margin-left: 10px;
}
.mb8{
  margin-bottom: 10px;
}
.tree-border {
    margin-top: 5px;
    width: 100%;
    border: 1px solid #e5e6e7;
    background: #fff none;
    border-radius: 4px;
}
</style>